/**
 * 维护描述转标签配置
 */
import type { OptionalFields } from '@gnlab/utils'
import { Service } from '@gnlab/utils'
import type { Services } from '@/services'
import { API } from '@/services/common/api'

export interface DescribeToTagsRule {
  id: number
  match: string // 匹配字符串，不带开头的 `$tag:` 和结尾的 `:$`
  tagIds: string[] // 匹配上后要打上的标签 ID
}

interface RespDescribeToTagsRule {
  Id: number
  Desc: string // 开头结尾固定带 `$tag:` 和 `:$`
  LabelIds: string | null
}

function formatDescribeToTagsRule(raw: RespDescribeToTagsRule): DescribeToTagsRule {
  return {
    id: raw.Id,
    match: removeSep(raw.Desc),
    tagIds: (raw.LabelIds ?? '').split(',').filter(v => v),
  }
}

/**
 * 移除、补充匹配字符串开头结尾的 `$tag:` 和 `:$`
 */
function removeSep(text: string) {
  return text.replace(/^\$(tag:)?/, '').replace(/:?\$$/, '')
}
function addSep(text: string) {
  return `$tag:${text}:$`
}

export class DescribeToTags extends Service<Services> {
  async load() {
    return API('/Config/GetDescToLabel', {
      formatter(data: RespDescribeToTagsRule[] | null) {
        return (data ?? []).map(formatDescribeToTagsRule)
      },
    })
  }

  async addOrUpdate(rule: OptionalFields<DescribeToTagsRule, 'id'>) {
    return API('/Config/SaveDescToLabel', {
      data: {
        Id: rule.id,
        Desc: addSep(rule.match),
        LabelIds: rule.tagIds.join(','),
      },
      formatter() {},
    })
  }

  async remove(id: number) {
    return API('/Config/RemoveDescToLabel', {
      data: { Id: id },
      formatter() {},
    })
  }
}
